﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using log4net;
using Microsoft.Win32;
using System.Management;

namespace QianBuo.Lottery.Server
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        CheckIssue ci;
        BackTask tb;
        string appName = "后台开奖程序";
        protected static ILog Log = Code.Commen.Log.GetLog("Server.MainForm");

        private void MainForm_Load(object sender, EventArgs e)
        {
            var auto = System.Configuration.ConfigurationManager.AppSettings["AutoRun"];
            
            if ("1".Equals(auto))
            {
                try
                {
                    string path = Application.ExecutablePath;
                    RegistryKey HKLM = Registry.LocalMachine;
                    RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
                    var tmp = Run.GetValue(appName);
                    if (tmp == null || path != tmp.ToString())
                        Run.SetValue(appName, path);
                    mnuAutoRun.Checked = true;
                }
                catch
                {
                    MessageBox.Show("自启动设置失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            /////// 判断连接是否有效
            var flag=new AccessData().CheckConnection();
            if (!flag)
            {
                btnStartOpen.Enabled = true;
                btnStopOpen.Enabled = false;
                MessageBox.Show("数据库连接失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ///////

            ci = CheckIssue.Current;
            tb = BackTask.Current;
            this.Run();
            StartAnimation();
        }

        public void StartAnimation()
        { 
            this.Opacity = 0;

            var t = new Thread(new ThreadStart(() =>
                {
                    Thread.Sleep(100);
                    var h = new Act(() =>
                        {
                            while (this.Opacity < 1)
                            {
                                this.Opacity += 0.1;
                                Thread.Sleep(100);
                            }
                            this.WindowState = FormWindowState.Minimized;
                        });
                    this.Invoke(h);
                }));
            t.Start();
        }

        delegate void Act();


        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.nfiIcon.Visible = false;
            System.Environment.Exit(0);
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        private void mnuAutoRun_Click(object sender, EventArgs e)
        {
            bool auto = !mnuAutoRun.Checked;

            try
            {
                string path = Application.ExecutablePath;
                RegistryKey HKLM = Registry.LocalMachine;
                RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
                var tmp = Run.GetValue(appName);
                if (auto)
                {
                    if (tmp == null || path != tmp.ToString())
                        Run.SetValue(appName, path);
                }
                else if (tmp != null)
                {
                    Run.DeleteValue(appName);
                }
                mnuAutoRun.Checked = auto;
            }
            catch
            {
                MessageBox.Show("自启动设置失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void nfimnuMainForm_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
                this.Hide();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = MessageBox.Show("退出程序将停止后台开奖，您确定要退出吗？", "退出提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void btnStartOpen_Click(object sender, EventArgs e)
        {
            /////// 判断连接是否有效
            var flag = new AccessData().CheckConnection();
            if (!flag)
            {
                btnStartOpen.Enabled = true;
                btnStopOpen.Enabled = false;
                MessageBox.Show("数据库连接失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ///////
            Run();
        }

        private void Run()
        {
            try
            {
                ci.Rrn();
                tb.Run();
            }
            catch (Exception ex)
            {
                nfiIcon.ShowBalloonTip(5000, "错误提示", ex.Message, ToolTipIcon.Error);
                if (Log.IsDebugEnabled)
                    Log.Debug(ex.Message, ex);
                else if (Log.IsErrorEnabled)
                    Log.Error(ex.Message);
                Stop();
            }
            btnStartOpen.Enabled = false ;
            btnStopOpen.Enabled = true;
        }

        private void Stop()
        {
            tb.Exit();
            ci.Exit(true);
            btnStartOpen.Enabled = true;
            btnStopOpen.Enabled = false;
            
        }

        private void btnStopOpen_Click(object sender, EventArgs e)
        {
            Stop();
        }

        private void nfiIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            nfimnuMainForm_Click(sender, e);
        }

        private void mnuRegest_Click(object sender, EventArgs e)
        {
            foreach (Form item in Application.OpenForms)
            {
                if (item is RegestForm)
                {
                    item.WindowState = FormWindowState.Normal;
                    return;
                }
            }
            new RegestForm().Show();
        }

    }
}
